#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2025 粤港澳大湾区（广东）国创中心

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

File: configLoad.py
Desc: Configuration loader for initializing SDK.
Author: xumanjia
Date: 2025-08-01
"""
import sys
import ctypes
import importlib
import os
import json
def init_NCTI_Config():
    jsonData = get_systemConfigJson()
    dllpath = jsonData["dllPath"]
    addKernelPath = jsonData["addKernelPath"]
    loadDLLs = jsonData["loadDLL"]
    #add dll path
    if False == os.path.isabs(dllpath):
        current_dir = os.path.dirname(os.path.abspath(__file__))
        dllpath =  current_dir+"/"+dllpath
    try:
        sys.path.insert(0, dllpath)
        for ker in addKernelPath:
            api_path = dllpath + "/" + ker
            if os.path.exists(api_path):
                os.add_dll_directory(api_path)
            else:
                print(f"Warning: DLL not found: {addDllPath}")
        #add dll
        for loadDll in loadDLLs:
            addDllPath = dllpath + "/" + loadDll
            if os.path.exists(addDllPath):
                ctypes.CDLL(addDllPath)
            else:
                print(f"Warning: DLL not found: {addDllPath}")
        #init ncti_python
        NCTI = importlib.import_module("ncti_python")
        if 1 != NCTI.Init(dllpath):
            return None
        return NCTI
    except:
        print("System path error or loading dll failure!")
        return None

def get_systemConfigJson():
    try:
        current_dir = os.path.dirname(os.path.abspath(__file__))
        jsonfile = current_dir + '/' + "systemConfig.json"
        with open(jsonfile, 'r') as file:
            data = json.load(file)
            return data
    except FileNotFoundError:
        print("文件未找到")
        return ""
    except json.JSONDecodeError:
        print("JSON 文件格式错误")
        return ""
    
global_scope = {}
NCTI = init_NCTI_Config()
if None != NCTI:
    global_scope["NCTI"] = NCTI
    global_scope["doc"] = NCTI.Document()
